//
//  WCUpdateRecordVC.m
//  WC
//
//  Created by wsj2015 on 16/1/25.
//  Copyright © 2016年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCUpdateRecordVC.h"
#import "WCRecordDesCell.h"
#import "WCRecordTimeCell.h"
#import "WCUpdatePicCell.h"
#import "WCImageManager.h"
#import "NSString+Utilities.h"
#import "WCUpdateImageModel.h"
#import "Constants.h"
#import "UMMobClick/MobClick.h"

@interface WCUpdateRecordVC ()

@property (nonatomic, copy) NSString *titleTxt;
@property (nonatomic, copy) NSString *contentTxt;

@property (nonatomic, assign) NSInteger openItem;

@property (nonatomic, retain) WCUpdatePicCell *picCell;
@property (nonatomic, strong) WCRecordDesCell *desCell;

@property (nonatomic, copy) NSString *postUrl;
@property (nonatomic,  copy) NSString *updateTime;

@property (nonatomic,  assign) WCUpdateRecordVCMode mode;

@property (nonatomic, retain) NSMutableArray *imageTitleArray;
@property (nonatomic, retain) NSMutableArray *openItemTitleArray;

//装字符串
@property (nonatomic,  retain) NSMutableArray *iamgeParamsArray;


@property (nonatomic,  assign) BOOL editAable;


@end

@implementation WCUpdateRecordVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self configUI];
    UITapGestureRecognizer *tap =[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewEndEditing)];
    [self.tableView addGestureRecognizer:tap];
   
  
}
- (void)viewEndEditing{
    [self.view endEditing:YES];
}
- (instancetype)initWithMode:(WCUpdateRecordVCMode)mode
{
    self = [super init];
    if (self) {
        self.imageTitleArray = [NSMutableArray array];
        self.mode = mode;
         self.editAable = YES;
        if (mode == WCUpdateRecordVCModeAdd) {
            self.postUrl = kAddFllowup;
        }else{
           self.postUrl = kUpdateFllowup;
        }
        self.openItem =1;//默认
       
    }
    return self;
}

#pragma mark -修改时 传进模型

//content = @"dsfadfa"
//createTime = 1453796441956;
//followupImage1 = "8235fbce-8c12-4326-93e2-7d992750adcf";
//followupImage2 = "e9419f0b-8170-4824-9b74-63688e131dc9";
//followupRight = 1;
//followupType = 2; 如果是1有护理上传 不可修改   2有本人上传  可修改 (护士端 : 有患者上传)
//id = 15;
//nurseId = 86;
//nurseName = "\U738b\U82cf\U8fdb";
//title = "\U6211\U662f\U738b\U82cf\U82cf";
- (void)setRecoredModel:(WCInforRecord *)recoredModel
{
    _recoredModel = recoredModel;
    self.titleTxt =recoredModel.title;
    self.updateTime =[NSString timeToString:[recoredModel.createTime longLongValue]];
    self.openItem =[recoredModel.followupRight integerValue];
    self.contentTxt = recoredModel.content;
    
    if ([recoredModel.followupType integerValue] ==1 && [[WCDefaultManager shareMg] nurseId] ==[recoredModel.nurseId integerValue]) {
        self.editAable = YES;
    }else{
        self.editAable = NO;
    }
    
    for (int i =0; i <3; i++) {
        WCUpdateImageModel *model =[[WCUpdateImageModel alloc] init];
         model.imageId = i;
        if (i ==0) {
            if (recoredModel.followupImage1&&![recoredModel.followupImage1 isEqualToString:@""]) {
                 model.imageName =recoredModel.followupImage1;
               
//                网路图
                 model.feature =2;
            }else{
//
//              占位图
                model.feature =0;
            
            }
           
        }
        if (i ==1) {
            if (recoredModel.followupImage2&&![recoredModel.followupImage2 isEqualToString:@""]) {
                model.imageName =recoredModel.followupImage2;
             
                model.feature =2;
            }else{
             
                model.feature =0;
                
            }
            
        }
        if (i ==2) {
            if (recoredModel.followupImage3&&![recoredModel.followupImage3 isEqualToString:@""]) {
                model.imageName =recoredModel.followupImage3;
            
                model.feature =2;
            }else{
            
                model.feature =0;
                
            }
            
        }
        [self.iamgeParamsArray  addObject:model];

    }
   
   
    [self.tableView reloadData];
    

}

- (NSMutableArray *)iamgeParamsArray
{
    if (_iamgeParamsArray ==nil) {
        _iamgeParamsArray =[NSMutableArray array];
    }
    return _iamgeParamsArray;

}
- (void)configUI{
    
  
    [self addRightBarButtonItemWithTitle:@"确定" target:self action:@selector(comfirm:)];
//    defineWeakSelf;
//    self.tableView.tapAction= ^(){
//        [weakSelf.tableView endEditing:YES];
//        [weakSelf.view endEditing:YES];
//    };
    
    
    if (self.mode ==WCUpdateRecordVCModeUpdate) {
        self.title =@"修改记录" ;
    }else{
         self.title =@"上传记录" ;
    }

    [self.tableView registerNib:[UINib nibWithNibName:@"WCRecordDesCell" bundle:nil] forCellReuseIdentifier:@"WCRecordDesCellId"];
    [self.tableView registerNib:[UINib nibWithNibName:@"WCRecordTimeCell" bundle:nil] forCellReuseIdentifier:@"WCRecordTimeCellId"];
    [self.tableView registerClass:[WCUpdatePicCell class] forCellReuseIdentifier:@"WCUpdatePicCellId"];
    

}
- (void)dealloc{
    
}
- (void)comfirm:(id)sender
{
    [self.tableView endEditing:YES];
    [self.view endEditing:YES];
    if (self.editAable !=YES) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"只有本人上传才可修改" withView:self.view];
        return;
    }
    [self checkWithparams];

}
- (NSArray *)openItemTitleArray{
    if (_openItemTitleArray ==nil) {
//        1.全公开、2.仅限本人和患者、3.仅限本人(必填)
        _openItemTitleArray = @[@"全公开",@"仅限本人和患者",@"仅限本人"];
    }
    return _openItemTitleArray;

}
#pragma mark -判断参数  是否合法

- (void)checkWithparams{
    //contactId:常用联系人ID(必填)
    //patientDisease:病情描述(必填)
    //recordType:档案类型：1伤口，2PICC，3妇幼，4慢性，5其他(必填)
    //isOpen:是否开放，0为不开放，1为开放。(必填)
    if (!self.desCell.titleTf.text || [self.desCell.titleTf.text isEqualToString:@""]) {
        [CoreSVP showSVPWithType:CoreSVPTypeCenterMsg Msg:@"标题不能为空~" duration:.8f allowEdit:NO beginBlock:nil completeBlock:nil];
        return;
    }
    if (!self.desCell.contentTxtView.text || [self.desCell.contentTxtView.text isEqualToString:@""]) {
        [CoreSVP showSVPWithType:CoreSVPTypeCenterMsg Msg:@"描述不能为空" duration:.8f allowEdit:NO beginBlock:nil completeBlock:nil];
        return;
    }
//    if (!self.illDescription || self.illDescription.length ==0) {
//        [CoreSVP showSVPWithType:CoreSVPTypeCenterMsg Msg:@"病情描述不能为空" duration:.8f allowEdit:NO beginBlock:nil completeBlock:nil];
//        return;
//    }
//    
    UIAlertView *alerView =[[UIAlertView alloc] initWithTitle:@"提示" message:@"是否确认提交" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"确认", nil];
    alerView.tag =500 +1;
    [alerView show];
    
    
}
- (void)pageBack{
    
    if (self.editAable) {
        NSString *message;
        NSString *btnTitle;
        if (self.mode ==WCUpdateRecordVCModeAdd) {
            message = @"是否放弃上传";
            btnTitle = @"放弃上传";
        }else{
            message = @"是否放弃修改";
            btnTitle = @"放弃修改";
            
        }
        UIAlertView *alerView =[[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:btnTitle otherButtonTitles:@"继续编辑", nil];
        alerView.tag = 500 +2;
        [alerView show];
    }else {
        [self.navigationController popViewControllerAnimated:YES];
    }
   

}
#pragma mark -警告栏事件
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 500 +1) {
        if (buttonIndex == 1) {
           
            
                 NSMutableArray *postArray =[NSMutableArray array];
                //增加记录
            
            
              //讲 cell 里返回来的模型 替换为本控制的模型
                self.iamgeParamsArray =self.picCell.allPics;
            
//                通用
                for (WCUpdateImageModel *model in self.picCell.allPics) {
                    //本地图并且不是占位图
                    if (model.feature ==1) {
                        [postArray addObject:model];
                    }
                   
                    
                }
                
                if (postArray.count>0) {
                     [self updatePicsByPost:postArray];
                }else{
                
                [self beginAddRecored];
                }
            
            
        }
    }else{
        if (buttonIndex == 0) {
            [self.navigationController popViewControllerAnimated:YES];;
        }
        
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 3;

}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
   
    defineWeakSelf;
    UITableViewCell *idcell;
    if (indexPath.row ==0) {
        WCRecordDesCell *cell =[tableView dequeueReusableCellWithIdentifier:@"WCRecordDesCellId" forIndexPath:indexPath];
        if (self.titleTxt) {
            cell.titleTf.text = self.titleTxt;
            
        }
        if (self.contentTxt) {
            cell.contentTxtView.text =self.contentTxt;
        }
//        cell.titleChanged = ^(NSString *title){
//            weakSelf.titleTxt =title;
//        };
//        cell.contentChanged = ^(NSString *content){
//            weakSelf.contentTxt =content;
//        };
        cell.editAable = self.editAable;
        self.desCell =cell;
        idcell =  cell;
    }
    if (indexPath.row ==2) {
        WCRecordTimeCell  *cell =[tableView dequeueReusableCellWithIdentifier:@"WCRecordTimeCellId" forIndexPath:indexPath];
        if (self.updateTime) {
            cell.titleLabel.text = self.updateTime;
        }
        cell.timeTf.text =self.openItemTitleArray[self.openItem -1];
       
        cell.titleArray = self.openItemTitleArray;
        cell.saveBlock = ^(NSString *title, NSInteger index){
            weakSelf.openItem = index+1;
            [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:0]] withRowAnimation:UITableViewRowAnimationBottom];
        };
          cell.editAable = self.editAable;
        idcell =  cell;
    }
    if (indexPath.row ==1) {
        WCUpdatePicCell *cell =[tableView dequeueReusableCellWithIdentifier:@"WCUpdatePicCellId" forIndexPath:indexPath];
       
        if (self.iamgeParamsArray) {
            cell.threePics = self.iamgeParamsArray;
        }
        
        idcell = cell;
        cell.editAble = self.editAable;
        self.picCell = cell;
        cell.delegateController =^(){
            return weakSelf;
        };
    }
    idcell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return idcell;
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    CGFloat num;
    if (indexPath.row ==0){
        num =143;
    }else if(indexPath.row ==2)
    {
        num =88;
    }else if(indexPath.row ==1)
    {
        num =110;
    }
    
    return num;

}

#pragma mark -新增记录
- (void)beginAddRecored{
    //    nurseId
    //    recordId 患者档案ID(选填)
    //title:标题(必填)
    //content:内容(必填)
    //followupType:随访类型:2患者上传(必填)
    //followupRight:随访权限：1.全公开、2.仅限本人和患者、3.仅限本人(必填)
    //    followupImage1,followupImage2,followupImage3(选填)
    //    [WCPopupLayerManager showLodingView];
    
    
    //修改
    //    id:(必填)  title:标题
    //content:内容
    //followupRight:随访权限：1.全公开、2.仅限本人和患者、3.仅限本人(必填)
    //    followupImage1,followupImage2,followupImage3(选填)
    defineWeakSelf;
    MBProgressHUD *hud= [[WCPopupLayerManager shareMg] showWithLabel:@"同步服务器" withView:self.view];
    
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    if (self.mode ==WCUpdateRecordVCModeAdd) {
        params[@"recordId"] = @(self.recordId);
        params[@"followupType"] =@(1);
        params[@"nurseId"] =@([[WCDefaultManager shareMg] nurseId]);
    }else{
      
        params[@"id"] = @([self.recoredModel.id integerValue]);
    }
    for (WCUpdateImageModel *model in self.iamgeParamsArray) {
        if (model.imageId ==0) {
            if (model.isDelete ==YES && model.feature ==0) {
                params[@"followupImage1"] =@"";
            }else if(model.isDelete ==0 && model.feature ==1){
                params[@"followupImage1"] = model.imageName;
            
            }
            
        }
        if (model.imageId ==1 ) {
            if (model.isDelete ==YES && model.feature ==0) {
                params[@"followupImage2"] =@"";
            }else if(model.isDelete ==0 && model.feature ==1){
                params[@"followupImage2"] = model.imageName;
                
            }
            
        }
        if (model.imageId ==2 ) {
            if (model.isDelete ==YES && model.feature ==0) {
                params[@"followupImage3"] =@"";
            }else if(model.isDelete ==0 && model.feature ==1){
                params[@"followupImage3"] = model.imageName;
                
            }
        }
    }
    params[@"followupRight"] =@(self.openItem);
    
    params[@"title"] = self.desCell.titleTf.text;
    params[@"content"] =self.desCell.contentTxtView.text;
    
    [[WCNetworkAccessManager sharedMg] POST:self.postUrl parameters:params success:^(NSDictionary *responseObject) {
        
        //友盟统计
        if (weakSelf.mode ==WCUpdateRecordVCModeAdd) {
           [MobClick event:AddFollowupRecord];
        }else{
            [MobClick event:MotifyFollowupRecord];
        }
        
        CoreSVPSuccess(responseObject[@"data"]);
        if (weakSelf.isAutoRefresh) {
            weakSelf.isAutoRefresh();
        }
        [weakSelf.navigationController popViewControllerAnimated:YES];
        
    } failure:nil netError:nil always:^{
        
        [hud hide:YES];
    }];

}

#pragma mark -上传图片
- (void)updatePicsByPost:(NSArray *)imageArray
{
    //一张一张传  后台返回字符串 没有标示
    defineWeakSelf;
    [CoreSVP showSVPWithType:CoreSVPTypeLoadingInterface Msg:@"上传图片中...." duration:.35f allowEdit:NO beginBlock:nil completeBlock:nil];
    __block int tag =0;
    __block int alwaysTag =0;
    for (int i = 0; i<imageArray.count; i++) {
        WCUpdateImageModel *model =imageArray[i];
        [[WCImageManager sharedMg] uploadMultiImage:@[model.bigImage] success:^(NSDictionary *responseObject) {
            tag ++;
            NSArray *dataArray =responseObject[@"data"];
            model.imageName =[dataArray.firstObject objectForKey:@"name"];
            if (tag ==imageArray.count) {
                [weakSelf beginAddRecored];
            }
                  
        } failure:nil always:^{
            alwaysTag ++;
            if ( tag ==imageArray.count) {
                [CoreSVP dismiss];
            }else if (alwaysTag ==imageArray.count){
                if (tag !=imageArray.count) {
                      CoreSVPError(@"服务器繁忙...");
                }
                [CoreSVP dismiss];
              
            }
            
        }];
    }
}

@end
